import {
  StyleSheet,
  View,
  TextInput,
  Image,
  ScrollView,
  TouchableOpacity,
  SafeAreaView,
} from "react-native";
import { ThemedText } from "@/components/ThemedText";
import { ThemedView } from "@/components/ThemedView";
import { Carousel } from "@/components/Carousel";
import { Colors } from "@/constants/Colors";
import { useState, useEffect } from "react";
import { Ionicons, MaterialIcons } from "@expo/vector-icons";
import { useRouter } from "expo-router";

// 轮播图数据
const bannerImages = [
  "https://tse2-mm.cn.bing.net/th/id/OIP-C.jdP04yEoxG10mcywseQj7gAAAA?rs=1&pid=ImgDetMain",
  "https://tse2-mm.cn.bing.net/th/id/OIP-C.jdP04yEoxG10mcywseQj7gAAAA?rs=1&pid=ImgDetMain",
  "https://tse2-mm.cn.bing.net/th/id/OIP-C.jdP04yEoxG10mcywseQj7gAAAA?rs=1&pid=ImgDetMain",
];

// 限时抢购数据
const flashSaleItems = [
  {
    id: 1,
    title: "蒙牛洗护香波 长效清洁 1000ml",
    originalPrice: 19.9,
    salePrice: 9.9,
  },
  {
    id: 2,
    title: "蒙牛洗护香波 长效清洁 1000ml",
    originalPrice: 19.9,
    salePrice: 9.9,
  },
  {
    id: 3,
    title: "蒙牛洗护香波 长效清洁 1000ml",
    originalPrice: 19.9,
    salePrice: 9.9,
  },
];

// 分类菜单数据
const menuItems = [
  {
    icon: <Ionicons name="phone-portrait" size={24} color="#666" />,
    text: "数码",
  },
  { icon: <Ionicons name="fish" size={24} color="#666" />, text: "生鲜" },
  { icon: <Ionicons name="shirt" size={24} color="#666" />, text: "女装" },
  {
    icon: <MaterialIcons name="local-mall" size={24} color="#666" />,
    text: "男装",
  },
  {
    icon: <MaterialIcons name="child-care" size={24} color="#666" />,
    text: "母婴",
  },
  {
    icon: <MaterialIcons name="local-drink" size={24} color="#666" />,
    text: "乳制品",
  },
  { icon: <MaterialIcons name="grass" size={24} color="#666" />, text: "粮油" },
  {
    icon: <MaterialIcons name="fastfood" size={24} color="#666" />,
    text: "零食",
  },
  { icon: <MaterialIcons name="spa" size={24} color="#666" />, text: "坚果" },
  { icon: <Ionicons name="home" size={24} color="#666" />, text: "家居" },
];

// 优惠券数据
const coupons = [
  { amount: 10, desc: "无门槛", type: "无门槛" },
  { amount: 10, desc: "无门槛", type: "无门槛" },
  { amount: 10, desc: "无门槛", type: "无门槛" },
];

// 添加倒计时工具函数
const formatNumber = (num: number) => {
  return num < 10 ? `0${num}` : num.toString();
};

// 1. 添加搜索历史和热搜功能
const searchData = {
  history: ["手机", "电脑", "耳机"],
  hot: ["iPhone 15", "华为", "小米手环"],
};

// 2. 添加活动专区
const activityZones = [
  {
    id: 1,
    title: "限时秒杀",
    icon: <Ionicons name="flash" size={24} color="#ff4d4f" />,
  },
  {
    id: 2,
    title: "领券中心",
    icon: <Ionicons name="ticket" size={24} color="#ff4d4f" />,
  },
  {
    id: 3,
    title: "拼团优惠",
    icon: <Ionicons name="people" size={24} color="#ff4d4f" />,
  },
  {
    id: 4,
    title: "签到领币",
    icon: <Ionicons name="calendar" size={24} color="#ff4d4f" />,
  },
];

// 3. 添加商品分类标签切换
const productTabs = [
  { id: 1, title: "推荐" },
  { id: 2, title: "新品" },
  { id: 3, title: "热卖" },
];

export default function HomeScreen() {
  const router = useRouter();

  // 添加倒计时状态
  const [countdown, setCountdown] = useState({
    hours: 6,
    minutes: 59,
    seconds: 38,
  });

  // 处理倒计时逻辑
  useEffect(() => {
    const timer = setInterval(() => {
      setCountdown((prev) => {
        let { hours, minutes, seconds } = prev;

        if (seconds > 0) {
          seconds--;
        } else {
          seconds = 59;
          if (minutes > 0) {
            minutes--;
          } else {
            minutes = 59;
            if (hours > 0) {
              hours--;
            } else {
              // 倒计时结束，重置为初始值
              hours = 6;
              minutes = 59;
              seconds = 38;
            }
          }
        }

        return { hours, minutes, seconds };
      });
    }, 1000);

    // 清理定时器
    return () => clearInterval(timer);
  }, []);

  return (
    <SafeAreaView style={styles.safeArea}>
      <ThemedView style={styles.container}>
        {/* 搜索栏 */}
        <View style={styles.searchBar}>
          <TextInput
            style={styles.searchInput}
            placeholder="请输入搜索内容"
            placeholderTextColor={Colors.text.placeholder}
          />
          <TouchableOpacity style={styles.iconButton}>
            <Ionicons name="chatbubbles" size={24} color="#666" />
          </TouchableOpacity>
          <TouchableOpacity style={styles.iconButton}>
            <Ionicons name="keypad" size={24} color="#666" />
          </TouchableOpacity>
        </View>

        <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
          {/* 轮播图 */}
          <Carousel images={bannerImages} height={180} borderRadius={12} />

          {/* 分类菜单 */}
          <View style={styles.menuSection}>
            <View style={styles.menuGrid}>
              {menuItems.map((item, index) => (
                <TouchableOpacity
                  key={index}
                  style={styles.menuItem}
                  onPress={() => {
                    router.push({
                      pathname: "/search/category/[id]",
                      params: { id: index + 1, name: item.text },
                    });
                  }}
                >
                  <View style={styles.menuIcon}>
                    <ThemedText style={styles.menuIconText}>
                      {item.icon}
                    </ThemedText>
                  </View>
                  <ThemedText style={styles.menuText}>{item.text}</ThemedText>
                </TouchableOpacity>
              ))}
            </View>
          </View>

          {/* 优惠券区域 */}
          <View style={styles.couponSection}>
            <View style={styles.sectionHeader}>
              <ThemedText style={styles.sectionTitle}>今日好券</ThemedText>
              <TouchableOpacity>
                <ThemedText style={styles.headerAction}>领券 {">"}</ThemedText>
              </TouchableOpacity>
            </View>
            <ScrollView
              horizontal
              showsHorizontalScrollIndicator={false}
              style={styles.couponList}
            >
              {coupons.map((coupon, index) => (
                <View key={index} style={styles.couponItem}>
                  <View style={styles.couponLeft}>
                    <View style={styles.couponAmount}>
                      <ThemedText style={styles.couponSymbol}>¥</ThemedText>
                      <ThemedText style={styles.couponValue}>
                        {coupon.amount}
                      </ThemedText>
                    </View>
                    <ThemedText style={styles.couponType}>
                      {coupon.type}
                    </ThemedText>
                  </View>
                  <TouchableOpacity style={styles.couponButton}>
                    <ThemedText style={styles.couponButtonText}>
                      立即领取
                    </ThemedText>
                  </TouchableOpacity>
                </View>
              ))}
            </ScrollView>
          </View>

          {/* 限时抢购 */}
          <View style={styles.flashSaleSection}>
            <View style={styles.sectionHeader}>
              <View style={styles.headerLeft}>
                <ThemedText style={styles.sectionTitle}>限时抢购</ThemedText>
                <View style={styles.countdown}>
                  <ThemedText style={styles.countdownText}>
                    {formatNumber(countdown.hours)}
                  </ThemedText>
                  <ThemedText style={styles.countdownSeparator}>:</ThemedText>
                  <ThemedText style={styles.countdownText}>
                    {formatNumber(countdown.minutes)}
                  </ThemedText>
                  <ThemedText style={styles.countdownSeparator}>:</ThemedText>
                  <ThemedText style={styles.countdownText}>
                    {formatNumber(countdown.seconds)}
                  </ThemedText>
                </View>
              </View>
              <TouchableOpacity>
                <ThemedText style={styles.headerAction}>
                  查看全部 {">"}
                </ThemedText>
              </TouchableOpacity>
            </View>

            <ScrollView
              horizontal
              showsHorizontalScrollIndicator={false}
              style={styles.flashSaleList}
            >
              {flashSaleItems.map((item) => (
                <TouchableOpacity
                  key={item.id}
                  style={styles.flashSaleItem}
                  onPress={() => {
                    router.push({
                      pathname: "/product/[id]",
                      params: { id: item.id },
                    });
                  }}
                >
                  <Image
                    source={{
                      uri: "https://tse2-mm.cn.bing.net/th/id/OIP-C.jdP04yEoxG10mcywseQj7gAAAA?rs=1&pid=ImgDetMain",
                    }}
                    style={styles.flashSaleImage}
                  />
                  <ThemedText numberOfLines={2} style={styles.flashSaleTitle}>
                    {item.title}
                  </ThemedText>
                  <View style={styles.priceRow}>
                    <ThemedText style={styles.salePrice}>
                      ¥{item.salePrice.toFixed(2)}
                    </ThemedText>
                    <ThemedText style={styles.originalPrice}>
                      ¥{item.originalPrice.toFixed(2)}
                    </ThemedText>
                  </View>
                </TouchableOpacity>
              ))}
            </ScrollView>
          </View>

          {/* 底部留白 */}
          <View style={styles.bottomPadding} />
        </ScrollView>
      </ThemedView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  container: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  searchBar: {
    flexDirection: "row",
    padding: 10,
    alignItems: "center",
  },
  searchInput: {
    flex: 1,
    height: 36,
    backgroundColor: Colors.background.secondary,
    borderRadius: 18,
    paddingHorizontal: 15,
    color: Colors.text.primary,
    fontSize: 14,
  },
  iconButton: {
    padding: 8,
  },
  content: {
    flex: 1,
    backgroundColor: "#FFFFFF",
  },
  sectionHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingHorizontal: 15,
    marginBottom: 12,
  },
  headerLeft: {
    flexDirection: "row",
    alignItems: "center",
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: "600",
    color: "#333333",
  },
  headerAction: {
    fontSize: 12,
    color: "#999999",
  },
  // 优惠券样式
  couponSection: {
    marginTop: 15,
    paddingVertical: 15,
    backgroundColor: "#FFFFFF",
  },
  couponList: {
    paddingLeft: 15,
  },
  couponItem: {
    width: 150,
    height: 80,
    backgroundColor: "#F8F8F8",
    borderRadius: 8,
    marginRight: 10,
    padding: 12,
    flexDirection: "row",
    alignItems: "center",
  },
  couponLeft: {
    flex: 1,
  },
  couponAmount: {
    flexDirection: "row",
    alignItems: "flex-end",
    marginBottom: 4,
  },
  couponSymbol: {
    fontSize: 14,
    color: Colors.functional.price,
    marginBottom: 2,
  },
  couponValue: {
    fontSize: 24,
    fontWeight: "bold",
    color: Colors.functional.price,
  },
  couponType: {
    fontSize: 12,
    color: "#999999",
  },
  couponButton: {
    backgroundColor: Colors.primary,
    paddingVertical: 6,
    paddingHorizontal: 10,
    borderRadius: 4,
  },
  couponButtonText: {
    color: "#FFFFFF",
    fontSize: 12,
  },
  // 限时抢购样式
  flashSaleSection: {
    backgroundColor: "#FFFFFF",
    paddingVertical: 15,
    marginTop: 10,
  },
  countdown: {
    flexDirection: "row",
    alignItems: "center",
    marginLeft: 10,
  },
  countdownText: {
    backgroundColor: "#333333",
    color: "#FFFFFF",
    fontSize: 12,
    paddingHorizontal: 4,
    paddingVertical: 2,
    borderRadius: 2,
    minWidth: 20,
    textAlign: "center",
  },
  countdownSeparator: {
    color: "#333333",
    marginHorizontal: 2,
    fontWeight: "bold",
  },
  flashSaleList: {
    paddingHorizontal: 10,
  },
  flashSaleItem: {
    width: 120,
    marginRight: 10,
  },
  flashSaleImage: {
    width: "100%",
    height: 120,
    borderRadius: 8,
    backgroundColor: Colors.background.tertiary,
    marginBottom: 8,
  },
  flashSaleTitle: {
    fontSize: 12,
    color: "#333333",
    marginBottom: 4,
    height: 32,
  },
  priceRow: {
    flexDirection: "row",
    alignItems: "baseline",
  },
  salePrice: {
    fontSize: 16,
    color: Colors.functional.price,
    fontWeight: "bold",
    marginRight: 4,
  },
  originalPrice: {
    fontSize: 12,
    color: Colors.text.tertiary,
    textDecorationLine: "line-through",
  },
  // 分类菜单样式
  menuSection: {
    backgroundColor: "#FFFFFF",
    paddingVertical: 15,
  },
  menuGrid: {
    flexDirection: "row",
    flexWrap: "wrap",
    paddingHorizontal: 10,
  },
  menuItem: {
    width: "20%",
    alignItems: "center",
    marginBottom: 15,
  },
  menuIcon: {
    width: 45,
    height: 45,
    backgroundColor: Colors.background.secondary,
    borderRadius: 10,
    justifyContent: "center",
    alignItems: "center",
    marginBottom: 6,
  },
  menuIconText: {
    fontSize: 24,
  },
  menuText: {
    fontSize: 12,
    color: "#666666",
  },
  // 底部留白
  bottomPadding: {
    height: 20,
  },
});
